package com.wrb.pwd.component;

import com.alibaba.fastjson.JSON;
import com.wrb.pwd.model.User;
import com.wrb.pwd.service.UserService;
import com.wrb.pwd.utils.PageUtils;

import javax.swing.*;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.List;

/**
 * @author wrb
 * @date 2019/9/17 11:07
 */
public class UserListPanel extends JPanel {

	private UserService us = UserService.getInstance();

	private JScrollPane jScrollPane = new JScrollPane();
	private JTable table;
	private JPopupMenu mPopupMenu;
	private JTextField txtSearch;
	private JButton jbSearch;
	private JButton jbPrevPage;
	private JButton jbNextPage;
	private Clipboard clipboard;

	private int pageNo;
	private int pageSize;
	private JLabel pageMsg;

	private UserListPanel() {
		super(new FlowLayout(FlowLayout.LEADING, 20, 20));
		createPopupMenu();
		txtSearch = new JTextField(20);
		jbSearch = new JButton("搜索");
		jbPrevPage = new JButton("上一页");
		jbNextPage = new JButton("下一页");
		clipboard = getToolkit().getSystemClipboard();
		pageMsg = new JLabel();
	}

	public static UserListPanel getInstance() {
		return Inner.INSTANCE;
	}

	private static class Inner {
		private static final UserListPanel INSTANCE = new UserListPanel();
	}

	public void init() {
		this.removeAll();
		this.repaint();
		createPopupMenu();
		txtSearch = new JTextField(20);
		jbSearch = new JButton("搜索");
		jbPrevPage = new JButton("上一页");
		jbNextPage = new JButton("下一页");
		this.revalidate();
	}

	public void initTable(JButton jbHome, String platform) {
		initPage();
		reloadTable(platform);
		this.add(jbHome);
		JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		jPanel.add(txtSearch);
		jPanel.add(jbSearch);
		this.add(jPanel);
		this.add(jScrollPane);
		this.add(jbPrevPage);
		this.add(jbNextPage);
		this.pageMsg.setText("共" + PageUtils.getInstance().getPages() + "页，您当前在第" + (pageNo + 1) + "页");
		this.add(pageMsg);
		this.revalidate();
		this.jbSearch.addActionListener(e -> {
			String searchStr = txtSearch.getText();
			initPage();
			reloadTable(searchStr);
		});
		this.jbPrevPage.addActionListener(e -> {
			pageNo = pageNo - 1;
			reloadTable(this.txtSearch.getText());
			changePageButtonStatus();
		});
		this.jbNextPage.addActionListener(e -> {
			pageNo = pageNo + 1;
			reloadTable(this.txtSearch.getText());
			changePageButtonStatus();
		});
	}

	private void changePageButtonStatus() {
		if (pageNo == 0) {
			jbPrevPage.setEnabled(false);
		} else {
			jbPrevPage.setEnabled(true);
		}
		if (pageNo + 1 >= PageUtils.getInstance().getPages()) {
			jbNextPage.setEnabled(false);
		} else {
			jbNextPage.setEnabled(true);
		}
	}

	/**
	 * 重新加载表格
	 *
	 * @param platform
	 */
	private void reloadTable(String platform) {
		createJScrollPane(platform);
		changePageButtonStatus();
		this.pageMsg.setText("共" + PageUtils.getInstance().getPages() + "页，您当前在第" + (pageNo + 1) + "页");
	}

	private void createJScrollPane(String platform) {
		PageUtils<User> page = us.getUserList(platform, pageNo, pageSize);
		List<User> userList = page.getList();
		String[][] tableDate = new String[userList.size()][6];
		for (int i = 0; i < userList.size(); i++) {
			tableDate[i][0] = userList.get(i).getId();
			tableDate[i][1] = userList.get(i).getPlatform();
			tableDate[i][2] = userList.get(i).getName();
			tableDate[i][3] = userList.get(i).getPassword();
			tableDate[i][4] = userList.get(i).getPhone();
			tableDate[i][5] = userList.get(i).getEmail();
		}
		String[] name = {"ID", "平台", "账户", "密码", "手机", "邮箱"};
		this.repaint();
		this.table = new JTable(tableDate, name);
		this.table.getColumnModel().getColumn(3).setPreferredWidth(160);
		TableColumnModel tcm = this.table.getColumnModel();
		TableColumn tc = tcm.getColumn(0);
		//隐藏ID列 用这个方法隐藏不能获取到id的值
//		this.table.removeColumn(tc);
		//建议用下面6行代码隐藏
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setMinWidth(0);
		tc.setWidth(0);
		table.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
		table.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);
		this.jScrollPane.setViewportView(table);
		this.jScrollPane.setPreferredSize(new Dimension(455, 343));
		this.table.addMouseListener(new java.awt.event.MouseAdapter() {
			@Override
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jTable1MouseClicked(evt);
			}
		});
	}

	private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
		mouseRightButtonClick(evt);
		mouseMidButtonClick(evt);
	}

	/**
	 * 鼠标中键事件
	 *
	 * @param evt
	 */
	private void mouseMidButtonClick(java.awt.event.MouseEvent evt) {
		if (evt.getButton() == java.awt.event.MouseEvent.BUTTON2) {
			//获得行位置
			int row = ((JTable) evt.getSource()).rowAtPoint(evt.getPoint());
			//获得列位置
			int col = ((JTable) evt.getSource()).columnAtPoint(evt.getPoint());
			//获取选中值
			String value = (String) this.table.getValueAt(row, col);
			StringBuilder showTip = new StringBuilder("选取区域内容为：");
			if (value.length() > 20) {
				int i = 20;
				while (i < value.length()) {
					showTip.append("\n");
					showTip.append(value, i - 20, i);
					i += 20;
				}
				showTip.append("\n");
				showTip.append(value, i - 20, value.length());
			} else {
				showTip.append("\n");
				showTip.append(value);
			}
			showTip.append("\n\n如要复制请按是，否则请按否");
			int confirmStatus = JOptionPane.showConfirmDialog(this, showTip, "选取内容", 0);
			//复制选中值
			if (confirmStatus == 0) {
				copy(value);
			}
		}
	}

	/**
	 * 鼠标右键点击事件
	 *
	 * @param evt
	 */
	private void mouseRightButtonClick(java.awt.event.MouseEvent evt) {
		//判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
		if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
			//通过点击位置找到点击为表格中的行
			int focusedRowIndex = this.table.rowAtPoint(evt.getPoint());
			if (focusedRowIndex == -1) {
				return;
			}
			//将表格所选项设为当前右键点击的行
			this.table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
			//弹出菜单
			mPopupMenu.show(this.table, evt.getX(), evt.getY());
		}
	}

	private void createPopupMenu() {
		mPopupMenu = new JPopupMenu();
		JMenuItem updateMenItem = new JMenuItem();
		updateMenItem.setText("  编辑  ");
		updateMenItem.addActionListener(evt -> {
			//获取user
			String id = (String) this.table.getValueAt(this.table.getSelectedRow(), 0);
			User user = us.getUser(id);

			UserUpdateDialog dialog = new UserUpdateDialog(this, user);
			int state = dialog.getReturnStatus();
			if (state == 0) {
				return;
			}
			reloadTable(this.txtSearch.getText());
		});
		JMenuItem delMenItem = new JMenuItem();
		delMenItem.setText("  删除  ");
		delMenItem.addActionListener(evt -> {
			//该操作需要做的事
			int deleteStatus = JOptionPane.showConfirmDialog(this, "确定要删除吗？", "删除提示", 1, 2);
			if (deleteStatus != 0) {
				return;
			}
			PasswordCheckDialog dialog = new PasswordCheckDialog(this);
			int state = dialog.getReturnStatus();
			if (state == 0) {
				return;
			}
			deleteUser();
			reloadTable(this.txtSearch.getText());
		});
		JMenuItem updatePasswordItem = new JMenuItem();
		updatePasswordItem.setText("  修改密码  ");
		updatePasswordItem.addActionListener(evt -> {
			//该操作需要做的事
			String id = (String) this.table.getValueAt(this.table.getSelectedRow(), 0);
			User user = us.getUser(id);
			UserPasswordGeneratorDialog dialog = new UserPasswordGeneratorDialog(this, user);
			reloadTable(this.txtSearch.getText());
		});
		JMenuItem copyMenItem = new JMenuItem();
		copyMenItem.setText("  复制JSON数据  ");
		copyMenItem.addActionListener(e -> {
			String id = (String) this.table.getValueAt(this.table.getSelectedRow(), 0);
			User user = us.getUser(id);
			copy(JSON.toJSONString(user));
		});
		JMenuItem copyPasswordMenItem = new JMenuItem();
		copyPasswordMenItem.setText("  复制密码  ");
		copyPasswordMenItem.addActionListener(e -> {
			String value = (String) this.table.getValueAt(this.table.getSelectedRow(), 3);
			copy(value);
		});
		JMenuItem copyEmailMenItem = new JMenuItem();
		copyEmailMenItem.setText("  复制邮箱  ");
		copyEmailMenItem.addActionListener(e -> {
			String value = (String) this.table.getValueAt(this.table.getSelectedRow(), 5);
			copy(value);
		});
		JMenuItem copyPhoneMenItem = new JMenuItem();
		copyPhoneMenItem.setText("  复制手机号  ");
		copyPhoneMenItem.addActionListener(e -> {
			String value = (String) this.table.getValueAt(this.table.getSelectedRow(), 4);
			copy(value);
		});
		JMenuItem showMoreMenItem = new JMenuItem();
		showMoreMenItem.setText("  用戶详细信息  ");
		showMoreMenItem.addActionListener(e -> {
			String value = (String) this.table.getValueAt(this.table.getSelectedRow(), 0);
			User user = us.getUser(value);
			new UserShowDialog(this, user);
		});

		mPopupMenu.add(updateMenItem);
		mPopupMenu.add(delMenItem);
		mPopupMenu.add(updatePasswordItem);
		mPopupMenu.add(copyPasswordMenItem);
		mPopupMenu.add(copyEmailMenItem);
		mPopupMenu.add(copyPhoneMenItem);
		mPopupMenu.add(showMoreMenItem);
		mPopupMenu.add(copyMenItem);
	}

	private void deleteUser() {
		String id = String.valueOf(this.table.getValueAt(this.table.getSelectedRow(), 0));
		boolean isSuccess = us.deleteUser(id);
		if (isSuccess) {
			JOptionPane.showMessageDialog(this, "删除成功", "删除结果", JOptionPane.INFORMATION_MESSAGE);
		} else {
			JOptionPane.showMessageDialog(this, "删除失败", "删除结果", JOptionPane.ERROR_MESSAGE);
		}
	}

	private void copy(String text) {
		StringSelection ss = new StringSelection(text);
		clipboard.setContents(ss, null);
	}

	private void initPage() {
		this.pageNo = 0;
		this.pageSize = 20;
	}
}
